<?php
/**
 * @version        $Id$
 * @author         master@xuewl.com
 * @copyright      Copyright (c) 2007 - 2013, Chongqing Zero Technology Co. Ltd.
 * @link           http://www.xuewl.com
**/
/**
 * 获取系统信息
 */
helpers('time');
function get_sysinfo() {
	$sys_info['os']             = PHP_OS;
	$sys_info['zlib']           = function_exists('gzclose');//zlib
	$sys_info['safe_mode']      = (boolean) ini_get('safe_mode');//safe_mode = Off
	$sys_info['safe_mode_gid']  = (boolean) ini_get('safe_mode_gid');//safe_mode_gid = Off
	$sys_info['timezone']       = function_exists("date_default_timezone_get") ? date_default_timezone_get() : L('no_setting');
	$sys_info['socket']         = function_exists('fsockopen') ;
	$sys_info['web_server']     = strpos($_SERVER['SERVER_SOFTWARE'], 'PHP')===false ? $_SERVER['SERVER_SOFTWARE'].'PHP/'.phpversion() : $_SERVER['SERVER_SOFTWARE'];
	$sys_info['phpv']           = phpversion();	
	$sys_info['fileupload']     = @ini_get('file_uploads') ? ini_get('upload_max_filesize') :'unknown';
	return $sys_info;
}

/**
 * 获取缓存
 * @author xuewl <master@xuewl.com>
 * @param  string $file 文件名
 * @param  string $dir  目录名
 * @return mixed
 */
function getcache($file, $dir = NULL) {
	$fileName = (!is_null($dir) ? 'caches_'.$dir.'/'.$file : $file);
	return F($fileName);
}

/**
 * 设置缓存
 * @author xuewl <master@xuewl.com>
 * @param  string 	$file 	缓存名
 * @param  mixed 	$value 	缓存值
 * @param  string 	$dir 	目录名
 * @return mixed
 */
function setcache($file, $value = NULL, $dir = NULL) {
	$fileName = (!is_null($dir) ? 'caches_'.$dir.'/'.$file : $file);
	return F($fileName, $value);
}

/* 删除缓存文件 */
function delcache($file, $dir = NULL) {
	$fileName = (!is_null($dir) ? 'caches_'.$dir.'/'.$file : $file);
	return F($fileName, NULL);
}

/* 字符集转换 */
function diconv($str, $in_charset, $out_charset = CHARSET, $ForceTable = FALSE) {
	$in_charset = strtoupper($in_charset);
	$out_charset = strtoupper($out_charset);

	if(empty($str) || $in_charset == $out_charset) {
		return $str;
	}
	$out = '';
	if(!$ForceTable) {
		if(function_exists('iconv')) {
			$out = iconv($in_charset, $out_charset.'//IGNORE', $str);
		} elseif(function_exists('mb_convert_encoding')) {
			$out = mb_convert_encoding($str, $out_charset, $in_charset);
		}
	}
	return $out;
}

/* 获取文件名（处理乱码） */
function _basename($filename){  
     return preg_replace('/^.+[\\\\\\/]/', '', $filename);  
}

function dimplode($array) {
	if(!empty($array)) {
		$array = array_map('addslashes', $array);
		return "'".implode("','", is_array($array) ? $array : array($array))."'";
	} else {
		return 0;
	}
}

function _dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype  = 'URLENCODE', $allowcurl = TRUE, $position = 0) {
	$return = '';
	$matches = parse_url($url);
	$scheme = $matches['scheme'];
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;

	if(function_exists('curl_init') && function_exists('curl_exec') && $allowcurl) {
		$ch = curl_init();
		$ip && curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".$host));
		curl_setopt($ch, CURLOPT_URL, $scheme.'://'.($ip ? $ip : $host).':'.$port.$path);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if($post) {
			curl_setopt($ch, CURLOPT_POST, 1);
			if($encodetype == 'URLENCODE') {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
			} else {
				parse_str($post, $postarray);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $postarray);
			}
		}
		if($cookie) {
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		}
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch);
		if($errno || $status['http_code'] != 200) {
			return;
		} else {
			return !$limit ? $data : substr($data, 0, $limit);
		}
	}

	if($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$header = "Accept: */*\r\n";
		$header .= "Accept-Language: zh-cn\r\n";
		$boundary = $encodetype == 'URLENCODE' ? '' : '; boundary='.trim(substr(trim($post), 2, strpos(trim($post), "\n") - 2));
		$header .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";
		$header .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$header .= "Host: $host:$port\r\n";
		$header .= 'Content-Length: '.strlen($post)."\r\n";
		$header .= "Connection: Close\r\n";
		$header .= "Cache-Control: no-cache\r\n";
		$header .= "Cookie: $cookie\r\n\r\n";
		$out .= $header.$post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$header = "Accept: */*\r\n";
		$header .= "Accept-Language: zh-cn\r\n";
		$header .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$header .= "Host: $host:$port\r\n";
		$header .= "Connection: Close\r\n";
		$header .= "Cookie: $cookie\r\n\r\n";
		$out .= $header;
	}

	$fpflag = 0;
	if(!$fp = @fsocketopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout)) {
		$context = array(
			'http' => array(
				'method' => $post ? 'POST' : 'GET',
				'header' => $header,
				'content' => $post,
				'timeout' => $timeout,
			),
		);
		$context = stream_context_create($context);
		$fp = @fopen($scheme.'://'.($ip ? $ip : $host).':'.$port.$path, 'b', false, $context);
		$fpflag = 1;
	}

	if(!$fp) {
		return '';
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if(!$status['timed_out']) {
			while (!feof($fp) && !$fpflag) {
				if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
					break;
				}
			}

			if($position) {
				for($i=0; $i<$position; $i++) {
					$char = fgetc($fp);
					if($char == "\n" && $oldchar != "\r") {
						$i++;
					}
					$oldchar = $char;
				}
			}

			if($limit) {
				$return = stream_get_contents($fp, $limit);
			} else {
				$return = stream_get_contents($fp);
			}
		}
		@fclose($fp);
		return $return;
	}
}


/**
* 判断字符类型
* @param $str  string 原始字符
* @return array {
    1 : 汉字数字英文的混合字符串
    2 : 汉字数字的混合字符串
    3 : 汉字英文的混合字符串
    4 : 数字英文的混合字符串
    5 : 纯汉字
    6 : 纯数字
    7 : 纯英文
    8 : 其它
}
*/
function checkstr($str){
    $output='';
    $a=ereg('['.chr(0xa1).'-'.chr(0xff).']', $str);
    $b=ereg('[0-9]', $str);
    $c=ereg('[a-zA-Z]', $str);
    if($a && $b && $c){ $output='1';}
    elseif($a && $b && !$c){ $output='2';}
    elseif($a && !$b && $c){ $output='3';}
    elseif(!$a && $b && $c){ $output='4';}
    elseif($a && !$b && !$c){ $output='5';}
    elseif(!$a && $b && !$c){ $output='6';}
    elseif(!$a && !$b && $c){ $output='7';}
    else{ $output = 8;}
    return $output;
}

/**
 * 电子邮箱格式判断
 * @param  string $email 字符串
 * @return bool
 */
function isemail($email) {
	if (!empty($email)) {
	    return preg_match('/^[a-z0-9]+([\+_\-\.]?[a-z0-9]+)*@([a-z0-9]+[\-]?[a-z0-9]+\.)+[a-z]{2,6}$/i', $email);
	}
	return FALSE;
}
function is_mobile($string){
	if (!empty($string)) {
		return preg_match('/^1[3|4|5|7|8][0-9]\d{4,8}$/', $string);
	}
	return FALSE;
} 

function genTree($rows, $id='id', $pid='parentid', $son='cell') {  
    $items = array();  
    foreach ($rows as $row) $items[$row[$id]] = $row;  
    foreach ($items as $item) $items[$item[$pid]][$son][$item[$id]] = &$items[$item[$id]];  
    return isset($items[0][$son]) ? $items[0][$son] : array();
}

/**
 * 时间格式化
 * @param  int $timestamp 时间戳
 * @param  string  $format    格式
 * @return string
 */
function dgmdate($timestamp=0, $format='Y-m-d H:i:s') {
	$times = intval($timestamp);
	if(!$times) return false;
	return date($format,$times);
}

/**
 * 随机字符串
 *
 * @return bool
 * @author master@xuew.com
 **/
function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	if($numeric) {
		$hash = '';
	} else {
		$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
		$length--;
	}
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

// 获取超全局变量
function getgpc($k, $type='GP') {
	$type = strtoupper($type);
	switch($type) {
		case 'G': $var = &$_GET; break;
		case 'P': $var = &$_POST; break;
		case 'C': $var = &$_COOKIE; break;
		default:
			if(isset($_GET[$k])) {
				$var = &$_GET;
			} else {
				$var = &$_POST;
			}
			break;
	}
	return isset($var[$k]) ? $var[$k] : NULL;
}

// 检测表单
function submitcheck($name, $type = 'P') {
	if(!getgpc($name)) {
		return FALSE;
	} else {
		$type = strtoupper($type);
		$fromhash = getgpc('fromhash');
		switch ($type) {
			case 'G':
				return IS_GET;
				break;
			case 'GP':
				return IS_GET || IS_POST;
				break;
			default:
				return IS_POST;
				break;
		}
		if (getgpc('fromhash') == session('FROMHASH')) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}

/**
 * DZ在线中文分词
 * @param $title string 进行分词的标题
 * @param $content string 进行分词的内容
 * @param $encode string API返回的数据编码
 * @return array 得到的关键词数组
 */
function dz_segment($title = '', $content = '', $encode = 'utf-8'){
    if($title == ''){
        return false;
    }
    $title = rawurlencode(strip_tags($title));
    $content = strip_tags($content);
    if(strlen($content)>2400){ //在线分词服务有长度限制
        $content =  mb_substr($content, 0, 800, $encode);
    }
    $content = rawurlencode($content);
    $url = 'http://keyword.discuz.com/related_kw.html?title='.$title.'&content='.$content.'&ics='.$encode.'&ocs='.$encode;
    $xml_array=simplexml_load_file($url);//将XML中的数据,读取到数组对象中
    $result = $xml_array->keyword->result;
    $data = array();
    foreach ($result->item as $key => $value) {
        array_push($data, (string)$value->kw);
    }
    if(count($data) > 0){
        return $data;
    }else{
        return false;
    }
}

/**
 * 字符串加解密
 * @param  string  $string    原始字符串
 * @param  string  $operation 加解密类型
 * @param  string  $key       密钥
 * @param  integer $expiry    有效期
 * @author xuewl <master@xuewl.com>
 * @return string
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key != '' ? $key : C('AUTHKEY'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

/**
 * 字符串添加反斜杠
 * @param  string|array  $string 字符串或数组
 * @param  bool $force
 * @return string|array
 */
function daddslashes($string, $force = 1) {
	if(is_array($string)) {
		$keys = array_keys($string);
		foreach($keys as $key) {
			$val = $string[$key];
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}


/**
 * 数据htmlspecialchars
 * @param  mixed $string 原始数据
 * @param  mixed $flags
 * @return mixed
 */
function new_html_special_chars($string, $flags = null) {
	return dhtmlspecialchars($string, $flags);
}
function dhtmlspecialchars($string, $flags = null) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val, $flags);
		}
	} else {
		if($flags === null) {
			$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
			if(strpos($string, '&amp;#') !== false) {
				$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
			}
		} else {
			if(PHP_VERSION < '5.4.0') {
				$string = htmlspecialchars($string, $flags);
			} else {
				if(strtolower(CHARSET) == 'utf-8') {
					$charset = 'UTF-8';
				} else {
					$charset = 'ISO-8859-1';
				}
				$string = htmlspecialchars($string, $flags, $charset);
			}
		}
	}
	return $string;
}

/**
 * 分页函数
 * @author xuewl <master@xuewl.com>
 * @param  int $totalRows 总数
 * @param  int $listRows  分页条数
 * @return string
 */
function page($totalRows = 0, $listRows = 20) {
	$Page = new \Common\Library\Page($totalRows, $listRows);
	$Page->setConfig('header', '<a class="a1">%TOTAL_ROW%条</a>');
	$Page->setConfig('prev', '上一页');
	$Page->setConfig('next', '下一页');
	$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
	return $Page->show();
}

/**
 * 分页函数
 *
 * @param $num 信息总数
 * @param $perpage 每页显示数
 * @param $curr_page 当前分页
 * @param $urlrule URL规则
 * @param $array 需要传递的数组，用于增加额外的方法
 * @return 分页
 */
function pages($num, $perpage = 20, $curr_page, $urlrule = '', $array = array(),$setpages = 6) {
	if(defined('URLRULE') && $urlrule == '') {
		$urlrule = URLRULE;
		$array = $GLOBALS['URL_ARRAY'];
	} elseif($urlrule == '') {
		$urlrule = url_par('page={$page}');
	}
	$multipage = '';
	if($num > $perpage) {
		$page = $setpages+1;
		$offset = ceil($setpages/2-1);
		$pages = ceil($num / $perpage);
		if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
		$from = $curr_page - $offset;
		$to = $curr_page + $offset;
		$more = 0;
		if($page >= $pages) {
			$from = 2;
			$to = $pages-1;
		} else {
			if($from <= 1) {
				$to = $page-1;
				$from = 2;
			}  elseif($to >= $pages) {
				$from = $pages-($page-2);
				$to = $pages-1;
			}
			$more = 1;
		}
		$multipage .= '<a class="page-wa">'.$num.L('page_item').'</a>';
		
		if($curr_page>0) {
			$multipage .= '<a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="page-wa">'.L('previous').'</a>';
			if($curr_page==1) {
				$multipage .= '<span>1</span>';
			} elseif($curr_page > 6 && $more) {
				$multipage .= '<a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
			} else {
				$multipage .= '<a href="'.pageurl($urlrule, 1, $array).'">1</a>';
			}
		}
		for($i = $from; $i <= $to; $i++) {
			if($i != $curr_page) {
				$multipage .= '<a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
			} else {
				$multipage .= '<span>'.$i.'</span>';
			}
		}


		if($curr_page<$pages) {
			if($curr_page<$pages-5 && $more) {
				$multipage .= '<em>...</em><a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a><a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="page-wa">'.L('next').'</a>';
			} else {
				$multipage .= '<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a><a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="page-wa">'.L('next').'</a>';
			}
		} elseif($curr_page==$pages) {
			$multipage .= '<span>'.$pages.'</span><a href="'.pageurl($urlrule, $curr_page, $array).'" class="page-wa">'.L('next').'</a>';
		} else {
			$multipage .= '<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a><a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="page-wa">'.L('next').'</a>';
		}
	}
	return $multipage;
}
/**
 * 返回分页路径
 *
 * @param $urlrule 分页规则
 * @param $page 当前页
 * @param $array 需要传递的数组，用于增加额外的方法
 * @return 完整的URL路径
 */
function pageurl($urlrule, $page, $array = array()) {
	if(strpos($urlrule, '~')) {
		$urlrules = explode('~', $urlrule);
		$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
	}
	$findme = array('{$page}');
	$replaceme = array($page);
	if (is_array($array)) foreach ($array as $k=>$v) {
		$findme[] = '{$'.$k.'}';
		$replaceme[] = $v;
	}
	$url = str_replace($findme, $replaceme, $urlrule);
	$url = str_replace(array('http://','//','~'), array('~','/','http://'), $url);
	return remove_xss($url);
}

/**
 * URL路径解析，pages 函数的辅助函数
 *
 * @param $par 传入需要解析的变量 默认为，page={$page}
 * @param $url URL地址
 * @return URL
 */
function url_par($par, $url = '') {
	if($url == '') $url = get_url();
	$pos = strpos($url, '?');
	if($pos === false) {
		$url .= '?'.$par;
	} else {
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($querystring, $pars);
		$query_array = array();
		foreach($pars as $k=>$v) {
			if($k != 'page') $query_array[$k] = $v;
		}
		$querystring = http_build_query($query_array).'&'.$par;
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	return $url;
}

/**
 * 获取当前页面完整URL地址
 */
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

/**
* 将字符串转换为数组
*
* @param	string	$data	字符串
* @return	array	返回数组格式，如果，data为空，则返回空数组
*/
function string2array($data) {
	if($data == '') return array();
	@eval("\$array = $data;");
	return $array;
}
/**
* 将数组转换为字符串
*
* @param	array	$data		数组
* @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
* @return	string	返回字符串，如果，data为空，则返回空
*/
function array2string($data, $isformdata = 1) {
	if($data == '') return '';
	if($isformdata) $data = dstripslashes($data);
	return var_export($data, TRUE);
}

/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function dstripslashes($string) {
	if(!is_array($string)) return stripslashes($string);
	foreach($string as $key => $val) $string[$key] = dstripslashes($val);
	return $string;
}

/**
 * 生成上传附件验证
 * @param $args   参数
 * @param $operation   操作类型(加密解密)
 */
function upload_key($args) {
	$pc_auth_key = md5(C('AUTH_KEY').$_SERVER['HTTP_USER_AGENT']);
	$authkey = md5($args.$pc_auth_key);
	return $authkey;
}

/**
 * 自动纠正URL地址格式
 * @param  [type] $url [description]
 * @return [type]      [description]
 */
function _froatURI ($url) {
	$url = str_replace("：", ":", $url);
	if(stripos($url,"https://") === 0) {
		return $url;
	} else {
		if(stripos($url,"http://http://") === 0) {
			$url = str_replace("http://http://", "", $url);
		}
		if(stripos($url,"http://") === false) {
			$url = 'http://'.$url;
		}		
	}
	return $url;
}

/**
 * 获取平阴
 * @param  string  $str  转换的字符串
 * @param  bool $ishead  是否为首字母
 * @param  bool $isclose 是否释放资源
 */
function getPinyin($str, $ishead = FALSE, $isclose = TRUE) {
    global $pinyins;
    $restr = '';
    $str = trim(iconv('UTF-8', 'GBK', $str));
    $slen = strlen($str);
    if($slen < 2) {
        return $str;
    }
    if(count($pinyins) == 0) {
        $fp = fopen(COMMON_PATH.'/Data/pinyin.dat', 'r');
        while(!feof($fp)) {
            $line = trim(fgets($fp));
            $pinyins[$line[0].$line[1]] = substr($line, 3, strlen($line)-3);
        }
        fclose($fp);
    }    

    for($i=0; $i<$slen; $i++) {
        if(ord($str[$i])>0x80) {
            $c = $str[$i].$str[$i+1];
            $i++;
            if(isset($pinyins[$c])) {
                if($ishead=== FALSE) {
                    $restr .= $pinyins[$c];
                } else {
                    $restr .= $pinyins[$c][0];
                }
            } else {
                $restr .= "_";
            }
        } else if( preg_match("/[a-z0-9]/i", $str[$i])) {
            $restr .= $str[$i];
        } else {
            $restr .= "_";
        }
    }
    if($isclose === TRUE) {
        unset($pinyins);
    }
    return $restr;
}

/**
 * IE浏览器判断
 * @author xuewl <master@xuewl.com>
 */
function is_ie() {
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
	if(strpos($useragent, 'msie ') !== false) return true;
	return false;
}

/**
 * 转义 javascript 代码标记
 *
 * @param $str
 * @return mixed
 */
 function trim_script($str) {
	if(is_array($str)){
		foreach ($str as $key => $val){
			$str[$key] = trim_script($val);
		}
 	}else{
 		$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
		$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
		$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
		$str = str_replace ( 'javascript:', 'javascript：', $str );
 	}
	return $str;
}

/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...') {
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	$length = intval($length-strlen($dot)-$length/3);
	$n = $tn = $noc = 0;
	while($n < strlen($string)) {
		$t = ord($string[$n]);
		if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
			$tn = 1; $n++; $noc++;
		} elseif(194 <= $t && $t <= 223) {
			$tn = 2; $n += 2; $noc += 2;
		} elseif(224 <= $t && $t <= 239) {
			$tn = 3; $n += 3; $noc += 2;
		} elseif(240 <= $t && $t <= 247) {
			$tn = 4; $n += 4; $noc += 2;
		} elseif(248 <= $t && $t <= 251) {
			$tn = 5; $n += 5; $noc += 2;
		} elseif($t == 252 || $t == 253) {
			$tn = 6; $n += 6; $noc += 2;
		} else {
			$n++;
		}
		if($noc >= $length) {
			break;
		}
	}
	if($noc > $length) {
		$n -= $tn;
	}
	$strcut = substr($string, 0, $n);
	$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	return $strcut.$dot;
}

/**
 * 生成标题样式
 * @param $style   样式
 * @param $html    是否显示完整的STYLE
 */
function title_style($style, $html = 1) {
	$str = '';
	if ($html) $str = ' style="';
	$style_arr = explode(';',$style);
	if (!empty($style_arr[0])) $str .= 'color:'.$style_arr[0].';';
	if (!empty($style_arr[1])) $str .= 'font-weight:'.$style_arr[1].';';
	if ($html) $str .= '" ';
	return $str;
}

/**
 * 组装生成ID号
 * @param $modules 模块名
 * @param $contentid 内容ID
 */
function id_encode($modules,$contentid) {
	return urlencode($modules.'-'.$contentid);
}

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}

/**
 * 获取内容地址
 * @param $catid   栏目ID
 * @param $id      文章ID
 * @param $allurl  是否以绝对路径返回
 */
function go($catid, $id, $allurl = 0) {
	$category = getcache('category', 'commons');
	$models = getcache('model', 'commons');	
	$id = (int) $id;
	$catid = (int) $catid;
	if(!$id || !isset($category[$catid])) return '';
	$modelid = $category[$catid]['modelid'];
	if(!$modelid) return '';
	$db = M($models[$modelid]['tablename']);
	$r = $db->getById($id, 'url');
	if (!empty($allurl)) {
		if (strpos($r['url'], '://')===false) {
			if (strpos($category[$catid]['url'], '://') === FALSE) {
				$site = siteinfo($category[$catid]['siteid']);
				$r['url'] = substr($site['domain'], 0, -1).$r['url'];
			} else {
				$r['url'] = $category[$catid]['url'].$r['url'];
			}
		}
	}
	return $r['url'];
}

function dheader($string, $replace = true, $http_response_code = 0) {
	$islocation = substr(strtolower(trim($string)), 0, 8) == 'location';
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($http_response_code) || PHP_VERSION < '4.3' ) {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if($islocation) {
		exit();
	}
}

function dhtml_entity_decode($string) {
	return html_entity_decode($string,ENT_QUOTES, 'utf-8');
}

function dhtmlentities($string) {
	return htmlentities($string,ENT_QUOTES, 'utf-8');
}

/**
 * 当前路径
 * 返回指定栏目路径层级
 * @param $catid 栏目id
 * @param $symbol 栏目间隔符
 */
function catpos($catid, $symbol=' > '){
	$category_arr = array();
	$category_arr = getcache('category', 'commons');
	if(!isset($category_arr[$catid])) return '';
	$pos = '';
	$siteurl = '';
	$arrparentid = array_filter(explode(',', $category_arr[$catid]['arrparentid'].','.$catid));
	foreach($arrparentid as $catid) {
		$url = $category_arr[$catid]['url'];
		if(strpos($url, '://') === false) $url = $siteurl.$url;
		$pos .= '<a href="'.$url.'">'.$category_arr[$catid]['catname'].'</a>'.$symbol;
	}
	return $pos;
}

/**
 * 获取子栏目
 * @param $parentid 父级id
 * @param $type 栏目类型
 * @param $self 是否包含本身 0为不包含
 * @param $siteid 站点Id
 */
function subcat($parentid = NULL, $type = NULL,$self = '0') {
	$category = getcache('category', 'commons');
	foreach($category as $id=>$cat) {
		if(($parentid === NULL || $cat['parentid'] == $parentid) && ($type === NULL || $cat['type'] == $type)) $subcat[$id] = $cat;
		if($self == 1 && $cat['catid'] == $parentid && !$cat['child'])  $subcat[$id] = $cat;
	}
	return $subcat;
}

function runhook($hookid) {
	if (empty($hookid)) return FALSE;
	return A('Common/Hook', 'Api')->run($hookid);
}

/**
 * 生成指定尺寸缩略图
 * @author xuewl <master@xuewl.com>
 */
function thumb($thumb, $width, $height) {
	return $thumb;
}

/**
 * 加载小助手
 * @author xuewl <master@xuewl.com>
 */
function helpers($file = '') {
	if (empty($file)) return FALSE;
	$dir = COMMON_PATH.'Helpers/';
	if (is_array($file)) {
		foreach ($file as $f) {
			require_once $dir.$file.'.helper.php';
		}
	} else {
		require_once $dir.$file.'.helper.php';
	}
}

/**
 * 取得文件扩展
 *
 * @param $filename 文件名
 * @return 扩展名
 */
function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

/**
 * 返回附件类型图标
 * @param $file 附件名称
 * @param $type png为大图标，gif为小图标
 */
function file_icon($file,$type = 'png') {
	$ext_arr = array('doc','docx','ppt','xls','txt','pdf','mdb','jpg','gif','png','bmp','jpeg','rar','zip','swf','flv');
	$ext = fileext($file);
	if($type == 'png') {
		if($ext == 'zip' || $ext == 'rar') $ext = 'rar';
		elseif($ext == 'doc' || $ext == 'docx') $ext = 'doc';
		elseif($ext == 'xls' || $ext == 'xlsx') $ext = 'xls';
		elseif($ext == 'ppt' || $ext == 'pptx') $ext = 'ppt';
		elseif ($ext == 'flv' || $ext == 'swf' || $ext == 'rm' || $ext == 'rmvb') $ext = 'flv';
		else $ext = 'do';
	}
	if(in_array($ext,$ext_arr)) return 'static/images/ext/'.$ext.'.'.$type;
	else return 'static/images/ext/blank.'.$type;
}

/**
 * 执行SQL语句
 * @param  string $sqlquery SQL语句，支持多条
 * @return bool
 */
function sqlexecute($sqlquery = '') {
	if(empty($sqlquery)) return FALSE;
	$sqlquery = str_replace('prefix_', C('DB_PREFIX'), $sqlquery);
	$version = M()->query("select version() as v;");
	$version = intval($version[0]['v']);
	if($version > '4.1' && C('DEFAULT_CHARSET')) {
	    $sqlquery = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8;", $sqlquery);
	}            
	$sqlquery = str_replace("\r", "\n", $sqlquery);
	$queriesarray = explode(";\n", trim($sqlquery));
	foreach ($queriesarray as $query) {
		if (substr($query, 0, 1) != '#' && substr($query, 0, 1) != '-') {
			M()->execute($query);
		}
	}
	return TRUE;
}

function getDbVersion($value='') {
	$version = M()->query("select version() as v;");
	return intval($version[0]['v']);
}

/**
 * 加载模板
 * @param  string $controller   模块名
 * @param  string $action 		方法名
 * @param  string $style    	风格名
 * @return string
 */
function template($file, $module = '', $style = '') {
	$module = empty($module) ? strtolower(MODULE_NAME) : trim($module);
	$file = empty($file) ? strtolower(ACTION_NAME) : trim($file);	
	$_default_style = C('DEFAULT_STYLE');
	$_default_theme = C('DEFAULT_THEME');
	$_style = ($_default_style) ? $_default_style : $_default_theme;
	$style = (empty($style)) ? $_style : 'default';
	$template = template_file($module, $file, $style);	
	$tpl = new \Common\Library\template();
	$tmplCacheFile = $tpl->loadTemplate($template);
	return $tmplCacheFile;
}

/**
 * 获取模板文件
 * @author xuewl <master@xuewl.com>
 */
function template_file($module = '', $file = '', $style = 'default') {
	$dep = C('TMPL_FILE_DEPR');
	$suffix = C('TMPL_TEMPLATE_SUFFIX');
	$tmpdir = C('VIEW_PATH').$style;
	$tplfile = $tmpdir.$dep.$module.$dep.$file.$suffix;
	/* 模板不存在时取默认模板 */
	if ($style != 'default' && !file_exists ($tplfile)) {
		$tplfile = C('VIEW_PATH').'default'.$dep.$module.$dep.$file.$suffix;
	}
	$tplfile = (!file_exists($tplfile)) ? MODULE_PATH.'Templates/'.$file.$suffix : $tplfile;
	if (!file_exists ($tplfile)) {
		die($tplfile.' is not exists!');
	}
	return strtolower(trim($tplfile));
}

/**
 * 分页函数
 * 
 * @param $num 信息总数
 * @param $curr_page 当前分页
 * @param $pageurls 链接地址
 * @return 分页
 */
function content_pages($num, $curr_page, $pageurls) {
	$multipage = '';
	$page = 11;
	$offset = 4;
	$pages = $num;
	$from = $curr_page - $offset;
	$to = $curr_page + $offset;
	$more = 0;
	if($page >= $pages) {
		$from = 2;
		$to = $pages-1;
	} else {
		if($from <= 1) {
			$to = $page-1;
			$from = 2;
		} elseif($to >= $pages) {
			$from = $pages-($page-2);
			$to = $pages-1;
		}
		$more = 1;
	}
	if($curr_page > 0) {
		$perpage = $curr_page == 1 ? 1 : $curr_page-1;
		$multipage .= '<a class="a1" href="'.$pageurls[$perpage][0].'">上一页</a>';
		if($curr_page==1) {
			$multipage .= ' <span>1</span>';
		} elseif($curr_page>6 && $more) {
			$multipage .= ' <a href="'.$pageurls[1][0].'">1</a>..';
		} else {
			$multipage .= ' <a href="'.$pageurls[1][0].'">1</a>';
		}
	}
	for($i = $from; $i <= $to; $i++) {
		if($i != $curr_page) {
			$multipage .= ' <a href="'.$pageurls[$i][0].'">'.$i.'</a>';
		} else {
			$multipage .= ' <span>'.$i.'</span>';
		}
	}
	if($curr_page<$pages) {
		if($curr_page<$pages-5 && $more) {
			$multipage .= ' ..<a href="'.$pageurls[$pages][0].'">'.$pages.'</a> <a class="a1" href="'.$pageurls[$curr_page+1][0].'">下一页</a>';
		} else {
			$multipage .= ' <a href="'.$pageurls[$pages][0].'">'.$pages.'</a> <a class="a1" href="'.$pageurls[$curr_page+1][0].'">下一页</a>';
		}
	} elseif($curr_page==$pages) {
		$multipage .= ' <span>'.$pages.'</span> <a class="a1" href="'.$pageurls[$curr_page][0].'">下一页</a>';
	}
	return $multipage;
}


/**
 * 生成SEO
 * @param $catid        栏目ID
 * @param $title        标题
 * @param $description  描述
 * @param $keyword      关键词
 */
function seo($catid = '', $title = '', $description = '', $keyword = '') {
	if (!empty($title))$title = strip_tags($title);
	if (!empty($description)) $description = strip_tags($description);
	if (!empty($keyword)) $keyword = str_replace(' ', ',', strip_tags($keyword));
	$cat = array();
	if (!empty($catid)) {
		$categorys = getcache('category', 'commons');
		$cat = $categorys[$catid];
		$cat['setting'] = string2array($cat['setting']);
	}	
	$site_title = C('SITE_TITLE');
	$site_description = C('description');
	$seo['site_title'] = !empty($site_title) ? $site_title : C('WEBNAME');
	$seo['keyword'] = !empty($keyword) ? $keyword : C('keyword');
	$seo['description'] = isset($description) && !empty($description) ? $description : (isset($cat['setting']['meta_description']) && !empty($cat['setting']['meta_description']) ? $cat['setting']['meta_description'] : (isset($site_description) && !empty($site_description) ? $site_description : ''));
	$seo['title'] =  (isset($title) && !empty($title) ? $title.' - ' : '').(isset($cat['setting']['meta_title']) && !empty($cat['setting']['meta_title']) ? $cat['setting']['meta_title'].' - ' : (isset($cat['catname']) && !empty($cat['catname']) ? $cat['catname'].' - ' : ''));
	foreach ($seo as $k=>$v) {
		$seo[$k] = str_replace(array("\n","\r"),	'', $v);
	}
	return $seo;
}

/**
 * 检测模型是否存在
 * @author xuewl <master@xuewl.com>
 * @param  string $module 模型名称
 * @return bool
 */
function module_exists($module = '') {
	if (empty($module)) return FALSE;
	$modules = getcache('module', 'commons');
	return (is_array($modules) && isset($modules[ucwords($module)]));
}

/**
 * 提示信息页面跳转，跳转地址如果传入数组，页面会提示多个地址供用户选择，默认跳转地址为数组的第一个值，时间为5秒。
 * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
 * @param string $msg 提示信息
 * @param mixed(string/array) $url_forward 跳转地址
 * @param int $ms 跳转等待时间
 */
function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
	if(defined('IN_ADMIN')) {
		include parent::$admin->admin_tpl('showmessage', 'admin');
	} else {
		include template('showmessage', 'common');
	}
	exit;
}


/**
 * 获取可用模板列表
 * @author xuewl <master@xuewl.com>
 */
function template_list($disable = 0) {
	$list = glob(TPL_PATH.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
	$arr = $template = array();
	foreach ($list as $key => $v) {
		$dirname = basename($v);
		if (file_exists($v.DIRECTORY_SEPARATOR.'config.php')) {
			$arr[$key] = include $v.DIRECTORY_SEPARATOR.'config.php';
			if (!$disable && isset($arr[$key]['disable']) && $arr[$key]['disable'] == 1) {
			}
		} else {
			$arr[$key]['name'] = $dirname;
		}
		$arr[$key]['dirname']=$dirname;
	}
	return $arr;
}

/**
 * 创建密码
 * @param  string $password 原始密码
 * @param  string $encrypt  加密因子
 * @return string
 */
function create_password($password ='', $encrypt = '') {
	return md5(md5($password.$encrypt));
}

/**
 * 调用系统的API接口方法（静态方法）
 * api('User/getName','id=5'); 调用公共模块的User接口的getName方法
 * api('Admin/User/getName','id=5');  调用Admin模块的User接口
 * @param  string  $name 格式 [模块名]/接口名/方法名
 * @param  array|string  $vars 参数
 */
function api($name,$vars=array()){
    $array     = explode('/',$name);
    $method    = array_pop($array);
    $classname = array_pop($array);
    $module    = $array? array_pop($array) : 'Common';
    $callback  = $module.'\\Api\\'.$classname.'Api::'.$method;
    if(is_string($vars)) {
        parse_str($vars,$vars);
    }
    return call_user_func_array($callback,$vars);
}

/**
 * 检查id是否存在于数组中
 *
 * @param $id
 * @param $ids
 * @param $s
 */
function check_in($id, $ids = '', $s = ',') {
	if(!$ids) return false;
	$ids = explode($s, $ids);
	return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
}

/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string) { 
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

    $parm = array_merge($parm1, $parm2); 

	for ($i = 0; $i < sizeof($parm); $i++) { 
		$pattern = '/'; 
		for ($j = 0; $j < strlen($parm[$i]); $j++) { 
			if ($j > 0) { 
				$pattern .= '('; 
				$pattern .= '(&#[x|X]0([9][a][b]);?)?'; 
				$pattern .= '|(&#0([9][10][13]);?)?'; 
				$pattern .= ')?'; 
			}
			$pattern .= $parm[$i][$j]; 
		}
		$pattern .= '/i';
		$string = preg_replace($pattern, '', $string); 
	}
	return $string;
}

/**
 * 调用关联菜单
 * @param $linkageid 联动菜单id
 * @param $id 生成联动菜单的样式id
 * @param $defaultvalue 默认值
 */
function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0) {
	$linkageid = intval($linkageid);
	$datas = array();
	$datas = getcache('linkage_'.$linkageid, 'linkage');
	$infos = $datas['data'];
	if($datas['style']=='1') {
		$title = $datas['title'];
		$container = 'content'.random(3).date('is');
		if(!defined('DIALOG_INIT_1')) {
			define('DIALOG_INIT_1', 1);
			$string .= '<script type="text/javascript" src="'.JS_PATH.'dialog.js"></script>';
		}
		if(!defined('LINKAGE_INIT_1')) {
			define('LINKAGE_INIT_1', 1);
			$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/pop.js"></script>';
		}
		$var_div = $defaultvalue && (ACTION_NAME=='edit' || ACTION_NAME=='account_manage_info'  || ACTION_NAME=='info_publish' || ACTION_NAME=='orderinfo') ? menu_linkage_level($defaultvalue,$linkageid,$infos) : $datas['title'];
		$var_input = $defaultvalue && (ACTION_NAME=='edit' || ACTION_NAME=='account_manage_info'  || ACTION_NAME=='info_publish') ? '<input type="hidden" name="info['.$id.']" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']" value="">';
		$string .= '<div name="'.$id.'" value="" id="'.$id.'" class="ib">'.$var_div.'</div>'.$var_input.' <input type="button" name="btn_'.$id.'" class="button" value="'.L('linkage_select').'" onclick="open_linkage(\''.$id.'\',\''.$title.'\','.$container.',\''.$linkageid.'\')">';
		$string .= '<script type="text/javascript">';
		$string .= 'var returnid_'.$id.'= \''.$id.'\';';
		$string .= 'var returnkeyid_'.$id.' = \''.$linkageid.'\';';
		$string .=  'var '.$container.' = new Array(';
		foreach($infos AS $k=>$v) {
			if($v['parentid'] == 0) {
				$s[]='new Array(\''.$v['linkageid'].'\',\''.$v['name'].'\',\''.$v['parentid'].'\')';
			} else {
				continue;
			}
		}
		$s = implode(',',$s);
		$string .=$s;
		$string .= ')';
		$string .= '</script>';
		
	} elseif($datas['style']=='2') {
		if(!defined('LINKAGE_INIT_1')) {
			define('LINKAGE_INIT_1', 1);
			$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/jquery.ld.js"></script>';
		}
		$default_txt = '';
		if($defaultvalue) {
				$default_txt = menu_linkage_level($defaultvalue,$linkageid,$infos);
				$default_txt = '["'.str_replace(' > ','","',$default_txt).'"]';
		}
		$string .= $defaultvalue && (ACTION_NAME=='edit' || ACTION_NAME=='account_manage_info'  || ACTION_NAME=='info_publish') ? '<input type="hidden" name="info['.$id.']"  id="'.$id.'" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']"  id="'.$id.'" value="">';

		for($i=1;$i<=$datas['setting']['level'];$i++) {
			$string .='<select class="pc-select-'.$id.'" name="'.$id.'-'.$i.'" id="'.$id.'-'.$i.'" width="100"><option value="">请选择菜单</option></select> ';
		}

		$string .= '<script type="text/javascript">
					$(function(){
						var $ld5 = $(".pc-select-'.$id.'");
						$ld5.ld({ajaxOptions : {"url" : "'.APP_PATH.'api.php?op=get_linkage&act=ajax_select&keyid='.$linkageid.'"},defaultParentId : 0,style : {"width" : 120}})	 
						var ld5_api = $ld5.ld("api");
						ld5_api.selected('.$default_txt.');
						$ld5.bind("change",onchange);
						function onchange(e){
							var $target = $(e.target);
							var index = $ld5.index($target);
							$("#'.$id.'-'.$i.'").remove();
							$("#'.$id.'").val($ld5.eq(index).show().val());
							index ++;
							$ld5.eq(index).show();								}
					})
		</script>';
			
	} else {
		$title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title'];
		$colObj = random(3).date('is');
		$string = '';
		if(!defined('LINKAGE_INIT')) {
			define('LINKAGE_INIT', 1);
			$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>';
			if(defined('IN_ADMIN')) {
				$string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">';
			} else {
				$string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">';
			}
		}
		$string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>';
		$string .= '<script type="text/javascript">';
		$string .= 'var colObj'.$colObj.' = {"Items":[';

		foreach($infos AS $k=>$v) {
			$s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},';
		}
		$string .= substr($s, 0, -1);
		$string .= ']};';
		$string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{';
		$string .= 'title:"'.$title.'",';
		$string .= 'value:"'.$defaultvalue.'",';
		$string .= 'width:100';
		$string .= '});';
		$string .= '</script>';
	}
	return $string;
}

/**
 * 联动菜单层级
 */

function menu_linkage_level($linkageid,$keyid,$infos,$result=array()) {
	if(array_key_exists($linkageid,$infos)) {
		$result[]=$infos[$linkageid]['name'];
		return menu_linkage_level($infos[$linkageid]['parentid'],$keyid,$infos,$result);
	}
	krsort($result);
	return implode(' > ',$result);
}
/**
 * 通过catid获取显示菜单完整结构
 * @param  $menuid 菜单ID
 * @param  $cache_file 菜单缓存文件名称
 * @param  $cache_path 缓存文件目录
 * @param  $key 取得缓存值的键值名称
 * @param  $parentkey 父级的ID
 * @param  $linkstring 链接字符
 */
function menu_level($menuid, $cache_file, $cache_path = 'commons', $key = 'catname', $parentkey = 'parentid', $linkstring = ' > ', $result=array()) {
	$menu_arr = getcache($cache_file, $cache_path);
	if (array_key_exists($menuid, $menu_arr)) {
		$result[] = $menu_arr[$menuid][$key];
		return menu_level($menu_arr[$menuid][$parentkey], $cache_file, $cache_path, $key, $parentkey, $linkstring, $result);
	}
	krsort($result);
	return implode($linkstring, $result);
}
/**
 * 通过id获取显示联动菜单
 * @param  $linkageid 联动菜单ID
 * @param  $keyid 菜单keyid
 * @param  $space 菜单间隔符
 * @param  $tyoe 1 返回间隔符链接，完整路径名称 3 返回完整路径数组，2返回当前联动菜单名称，4 直接返回ID
 * @param  $result 递归使用字段1
 * @param  $infos 递归使用字段2
 */
function get_linkage($linkageid, $keyid, $space = '>', $type = 1, $result = array(), $infos = array()) {
	if($space=='' || !isset($space))$space = '>';
	if(!$infos) {
		$datas = getcache('linkage_'.$keyid, 'linkage');
		$infos = $datas['data'];
	}
	if($type == 1 || $type == 3 || $type == 4) {
		if(array_key_exists($linkageid,$infos)) {
			$result[]= ($type == 1) ? $infos[$linkageid]['name'] : (($type == 4) ? $linkageid :$infos[$linkageid]);
			return get_linkage($infos[$linkageid]['parentid'], $keyid, $space, $type, $result, $infos);
		} else {
			if(count($result)>0) {
				krsort($result);
				if($type == 1 || $type == 4) $result = implode($space,$result);
				return $result;
			} else {
				return $result;
			}
		}
	} else {
		return $infos[$linkageid]['name'];
	}
}

function mb_unserialize($serial_str) {
    $serial_str = str_replace ( "\r", "", $serial_str );
    $serial_str = preg_replace ( '!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
    return unserialize ( $serial_str );
}

function get_document_info($modelid, $id, $modelinfo = TRUE) {
	$models = getcache('model', 'commons');
	$model = $models[$modelid];
	$tablename = $model['tablename'];
	$info = M($tablename)->where(array('id' => $id))->find();
	if ($modelinfo == TRUE) {
		$modelinfo = M($tablename.'_data')->where(array('id' => $id))->find();
		$info = array_merge($info, $modelinfo);
	}
	require_once CACHE_MODEL_PATH.'content_output.class.php';
	$model_output = new \content_output($modelid, $info['catid']);
	$result = $model_output->get($info);
	return $result;
}

/**
 * 获取用户头像
 * @author xuewl <master@xuewl.com>
 */
function getavatar($uid = 0, $type = 'url') {
    $suid = sprintf("%09d", $uid);
    $dir1 = substr($suid, 0, 3);
    $dir2 = substr($suid, 3, 2);
    $dir3 = substr($suid, 5, 2);
    $rootDir = SITE_PATH.'/uploadfile/avatar/';
    $userDir = $dir1.'/'.$dir2.'/'.$dir3.'/';
    $fileDir = $rootDir.$userDir.$uid.'_avatar.jpg';
    if (!file_exists($fileDir)) {
    	$result = $rootDir.'avatar.jpg';
    } else {
    	$result = $fileDir;
    }
    return ($type == 'url') ? str_replace(SITE_PATH, __ROOT__, $result) : $result;
}

/**
 * 查询指定会员信息
 * @param  int  	$uid     会员ID
 * @param  string  	$field   指定字段
 * @param  boolean 	$ismodel 是否读取附加模型
 * @return mixed
 */
function getUserInfo($uid, $field = '', $ismodel = false) {
	$uid = (int) $uid;
	$uid = (is_numeric($uid) && $uid > 0) ? (int) $uid : (int) cookie('_userid');
	if($uid < 1) return false;
	$userinfo = D('member')->getByUserid($uid);
	if(!$userinfo) return FALSE;
	/* 查询模型数据 */
	if($ismodel === TRUE) {
		$models = getcache('model', 'commons');
		$tableName = $models[$userinfo['modelid']]['tablename'];
		if ($tableName) {
			$modelinfo = M($tableName)->getByUserid($uid);
			if ($modelinfo) {
				$userinfo = array_merge($userinfo, $modelinfo);
			}
		}
	}
	if (empty($field)) {		
		return $userinfo;
	} else {
		return $userinfo[$field];
	}
}


/* 字符串隐藏 */
function get_encode($str) {
    return $str ? cutstr($str, 3, '***').substr($str, -1) : '';
}


/**
 *  字符串提取函数
 *
 * @access    global
 * @param     string  $string   待截取的原字符串
 * @param     number  $length   截取字符串的长度
 * @param     string  $dot      超过部分字符代替
 * @return    string
 */
function cutstr($string, $length, $dot = ' ...') {
    if(strlen($string) <= $length) {
        return $string;
    }
    $pre = chr(1);
    $end = chr(1);
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

    $strcut = '';
    if(strtolower(CHARSET) == 'utf-8') {
        $n = $tn = $noc = 0;
        while($n < strlen($string)) {
            $t = ord($string[$n]);
            if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1; $n++; $noc++;
            } elseif(194 <= $t && $t <= 223) {
                $tn = 2; $n += 2; $noc += 2;
            } elseif(224 <= $t && $t <= 239) {
                $tn = 3; $n += 3; $noc += 2;
            } elseif(240 <= $t && $t <= 247) {
                $tn = 4; $n += 4; $noc += 2;
            } elseif(248 <= $t && $t <= 251) {
                $tn = 5; $n += 5; $noc += 2;
            } elseif($t == 252 || $t == 253) {
                $tn = 6; $n += 6; $noc += 2;
            } else {
                $n++;
            }

            if($noc >= $length) {
                break;
            }

        }
        if($noc > $length) {
            $n -= $tn;
        }

        $strcut = substr($string, 0, $n);

    } else {
        for($i = 0; $i < $length; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
        }
    }

    $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

    $pos = strrpos($strcut, chr(1));
    if($pos !== false) {
        $strcut = substr($strcut,0,$pos);
    }
    return $strcut.$dot;
}

/**
 * 检查会员是否登录
 * @author xuewl <master@xuewl.com>
 */
function is_login() {
	$userid = (int) cookie('_userid');
	if ($userid < 1) {
		return FALSE;
	}
	return getUserInfo($userid);
}

/**
 * 校验验证码
 * @author xuewl <master@xuewl.com>
 */
function checkVerify($string, $reset = TRUE) {
	$Verify = new \Think\Verify();
	$Verify->reset = $reset;
	return $Verify->check($string);
}


/* 生成文件 */
function dmkdir($dir, $mode = 0777, $makeindex = TRUE){
	if(!is_dir($dir)) {
		dmkdir(dirname($dir), $mode, $makeindex);
		@mkdir($dir, $mode);
		if(!empty($makeindex)) {
			@touch($dir.'/index.html'); @chmod($dir.'/index.html', 0777);
		}
	}
	return true;
}
/**
 * 转换字节数为其他单位
 *
 *
 * @param	string	$filesize	字节大小
 * @return	string	返回大小
 */
function sizecount($filesize) {
	if ($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
	} elseif ($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	} else {
		$filesize = $filesize.' Bytes';
	}
	return $filesize;
}


function sql_split($sql, $tablepre) {
    if ($tablepre != "prefix_")
        $sql = str_replace("prefix_", $tablepre, $sql);
    $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);

    if ($r_tablepre != $s_tablepre)
        $sql = str_replace($s_tablepre, $r_tablepre, $sql);
    $sql = str_replace("\r", "\n", $sql);
    $ret = array();
    $num = 0;
    $queriesarray = explode(";\n", trim($sql));
    unset($sql);
    foreach ($queriesarray as $query) {
        $ret[$num] = '';
        $queries = explode("\n", trim($query));
        $queries = array_filter($queries);
        foreach ($queries as $query) {
            $str1 = substr($query, 0, 1);
            if ($str1 != '#' && $str1 != '-')
                $ret[$num] .= $query;
        }
        $num++;
    }
    return $ret;
}

/**
 * 代码广告展示函数
 * @param intval $siteid 所属站点
 * @param intval $id 广告ID
 * @return 返回广告代码
 */
function show_ad($id) {
	$id = intval($id);
	if(!$id) return false;
	$p = D('Poster');
	$r = $p->where(array('spaceid'=>$id))->field( 'disabled, setting')->order('id ASC')->find();
	if ($r['setting']) {
		$c = string2array($r['setting']);
	} else {
		$r['code'] = '';
	}
	return $c['code'];
}

/**
 * 文件下载
 * @param $filepath 文件路径
 * @param $filename 文件名称
 */
function file_down($filepath, $filename = '') {
	if(!$filename) $filename = basename($filepath);
	if(is_ie()) $filename = rawurlencode($filename);
	$filetype = fileext($filename);
	$filesize = sprintf("%u", filesize($filepath));
	if(ob_get_length() !== false) @ob_end_clean();
	header('Pragma: public');
	header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Cache-Control: pre-check=0, post-check=0, max-age=0');
	header('Content-Transfer-Encoding: binary');
	header('Content-Encoding: none');
	header('Content-type: '.$filetype);
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	header('Content-length: '.$filesize);
	readfile($filepath);
	exit;
}

/* 计算当前会员的代理级别 */
function getAgentLevel($money) {
	$member_setting = getcache('setting', 'member');
	$cash_config = $member_setting['cash_config'];
	$arr = array_keys($cash_config);
	rsort($arr);
	$new_arr = $arr;
	$new_arr[] = $money;
	rsort($new_arr);
	$level = array_search($money, $new_arr);
	$level = $arr[$level];
	return $cash_config[$level];
}


/**
 * 用户提现ID
 * @param  int  $uid   用户ID
 * @param  int  $money 提现的U币
 * @param  int 	$level 推荐级别
 * @return mixed
 */
function docrsh($uid, $money, $level = 0) {
	$member_setting = getcache('setting', 'member');
	$cash_config = $member_setting['cash_config'];
	$uid = (int) $uid;
	$money = (int) $money;
	$sqlmap = array();
	$sqlmap['userid'] = $uid;
	if($uid < 1 || $money < 1) return FALSE;
	$db = M('Member');
	$userinfo = $db->getByUserid($uid);
	if(!$userinfo) return FALSE;
	extract($userinfo);
	$cash_config = getAgentLevel($money);
	if ($level == 0) {
		if($u_coin < $money) return FALSE;
		$db->where($sqlmap)->setDec("u_coin", $money);//扣除用户积分
	} else {
		$money = (int) $cash_config[$level];
		if($money > 0) {
			$db->where($sqlmap)->setInc("u_coin", $money);
			score_change($uid,'推荐提现奖励',$money,'rec',1);
		}		
	}
	if ($agent_id > 0) {
		$level++;
		docrsh($agent_id, $money, $level);
	}
	return TRUE;
}

/**
 * 积分变化
 * @param  int  $userid  用户ID
 * @param  int  $reason 发生原因
 * @param  int 	$score 积分变换
 * @param  int  $type  类型（U币、U豆）
 * @param  int  $change +/-标志（1为+，0为-）
 * @return mixed
 */

function score_change($userid,$reason,$score,$type,$change,$taskid = '',$extra = ''){
	$infos['userid']=$userid;
	$infos['posttime']=time();
	$infos['reason']=$reason;
	$infos['change']=$score;
	$infos['status']=1;
	$infos['c_type']=$change;
	$infos['u_type']=$type;
	$infos['taskid']=$taskid;
	$infos['extra']=$extra;
	$result=D('Score')->add($infos);
	return $result;
}

function doFormatMoney($money){
    $tmp_money = strrev($money);
    $format_money = ""; 
	for($i = 3;$i<strlen($money);$i+=3){
		$format_money .= substr($tmp_money,0,3).",";
		$tmp_money = substr($tmp_money,3);
	}
    $format_money .=$tmp_money;
    $format_money = strrev($format_money); 
    return $format_money;
}

function is_sign($uid) {
	$db = M('MemberSign');
	$sqlmap = array();
	$sqlmap['uid'] = $uid;
	$sqlmap['_string'] = "DATE_FORMAT(FROM_UNIXTIME(dateline),'%Y%m%d') = DATE_FORMAT(NOW(),'%Y%m%d')";
	return ($db->where($sqlmap)->count()) ? TRUE : FALSE;
}

function exchange_money($coin){
	$config = getcache('setting', 'member');
	$price=ceil($coin/$config['u_coin']);
	return $price;

}

function type_change(){
  $config = getcache('setting', 'member');
  $coin=$config['type_config'];
  return $coin;
}